﻿$(function () {
    $.ui.dialog.defaults.bgiframe = true;
    // the modules toolbox
    $('.tool-box li div').draggable({
        connectToSortable: '.column',
        helper: 'clone',
        appendTo: 'body'        
    });

    // the designer mode module drag and drop support
    $('.column').sortable({
        connectWith: '.column',
        handle: '.title-bar',
        cursor: 'move',
        placeholder: 'placeholder',
        forcePlaceholderSize: true,
        opacity: 0.4,
        distance: 5,
        stop: function (event, ui) {
            ui.item.css({ 'top': '0', 'left': '0' }); //Opera fix
            //if it is newly added module
            addTool(ui.item[0]);
            // update modules order
            updateModulesData();
        }
    }).disableSelection();
    
    //menu     
    $('.nav .current-page').parents('.nav .nav-main li').children('a').addClass('current-page');
    $('.nav li.nav-container').addClass('nav-container1');
    $('.nav li.nav-container').hover(function () {
        $(this).removeClass('nav-container1').addClass('nav-container2');
    }, function () {
        $(this).removeClass('nav-container2').addClass('nav-container1');
    });

    $('.nav .nav-sub').hover(function () {
        $(this).parent('li').children('a').addClass('active');
    }, function () {
        $(this).parent('li').children('a').removeClass('active');
    });
    
    $('.pane-title').hide();
    $('#show-panes').change(function () {
        $('.pane-title').toggle();
        $('.dragbox').toggleClass('border-light');
    }); 
//    $('.dragbox .title-bar').hide();
//    $('.dragbox').hover(function () {
//        $(this).children('.title-bar').show(); 
//    }, function () {
//        $(this).children('.title-bar').hide();
//    });

    // collapse expand module
    $('.dragbox .title-bar .buttons .expand-collapse').live('click', function () {
        $(this).parents('.dragbox').children('.dragbox-content').toggle();
    });
    // show module settings
    $('.dragbox .title-bar .buttons .configure').live('click', function () {
        // remove leading #Configure
        var moduleId = $(this).attr("href").substr(10);
        configureModule(moduleId, this);
    });
    // show module help
    $('.dragbox .title-bar .buttons .help').live('click', function () {
        // remove leading #Help
        var moduleId = $(this).attr("href").substr(5);
        configureModule(moduleId, this, 2);
    });
    // delete module
    $('.dragbox .title-bar .buttons .delete').live('click', function () {
        if (!confirm('Are you sure?'))
            return false;
        // remove leading #Delete
        var moduleId = $(this).attr("href").substr(7);
        deleteModule(moduleId, this);
    });
});

function addTool(which) {
    // add new module
    if($(which).hasClass('new-module')){ 
        var pane = $(which).parents('.column').attr('id');
        var pageid = $('.CurrentPageClass').val();
        var moduleInstalledId = $(which).attr('id');
        addModule($(which),moduleInstalledId, pageid, pane);
    }
    // add orphan module    
    if ($(which).hasClass('orphan-module')) {
       // this module already exist so just refresh its contents
        var moduleId = $(which).attr('id');
        // now this module is part of the webpage just hide it from the orphan modules list
        $('.tool-box li div#' + moduleId).parent('li').hide();
        // if orphan module list is completely empty after hidding all the orphan modules just hide it as well
        if($('.tool-box li div.orphan-module').parents('ul.tool-box li').filter(':visible').length == 0)
            $('.tool-box li div.orphan-module').parents('ul.tool-box').parent('li').hide();        
        $.post('Admin/Pages/_Modules/InplaceRendering.aspx?ModuleId=' + moduleId , function(data){
            $(which).before(data);
            $(which).prev('.dragbox').addClass('newly-added-module');
            $(which).remove();                
            });
    }
}

function addModule(which, moduleId, pageid, pane){	 
    $.post('Admin/Pages/_Modules/ModuleController.aspx?AddModule=True&InstalledModuleId=' + moduleId + '&PageId=' + pageid + '&Pane=' + pane, function(data) {                
        $(which).before(data);
        $(which).prev('.dragbox').addClass('newly-added-module');
        $(which).remove();
    });                
}


function updateModulesData(){
	var items=[];
	var pageid = $('.CurrentPageClass').val();
	$('.column').each(function(){
		var columnId=$(this).attr('id');
		$('.dragbox', this).each(function(i){
			//Create Item object for current panel
			var item={
				moduleid: $(this).attr('id'),
				pageid: pageid,
				order : i,
				pane: columnId				
			};
			//Push item object into items array
			items.push(item);
		});
	});
	//Assign items array to sortorder JSON variable
	var sortorder={ items: items };
	//Pass sortorder variable to server using ajax to save state
	ShowProgress('Updating the Server...');
	$.post('Admin/Pages/_Modules/ModuleController.aspx?UpdatePanes=True', 'data='+$.toJSON(sortorder), function(response){
		//if(response=="success")			
			HideProgress();
	});
}

function deleteModule(ModuleId, source){	                
    ShowProgressInsideModule(source);
    $.post('Admin/Pages/_Modules/ModuleController.aspx?DeleteModule=True&ModuleId=' + ModuleId, function(response){
    if(response=="success"){            
            var parent = $(source).parents('.dragbox');
            parent.fadeOut(500);            
		    setTimeout(function(){
			    parent.remove();
		    }, 2000);
		}
    });
    HideProgressInsideModule(source);
}
       
function configureModule(ModuleId, source, ActiveTab){
    ShowProgressInsideModule(source);
    $('#basic-modal-container').html('<div id="basic-modal-content" title="Module Settings" style="display: none"></div>');    
    $.post('Admin/Pages/_Modules/ModuleController.aspx?ModuleSettings=True&ModuleId=' + ModuleId, function(data) {                            
        $('#basic-modal-content').html(data);
        $('#module_settings_tabs').tabs();
        if(ActiveTab > 0)
            $('#module_settings_tabs').tabs('select', ActiveTab);
        HideProgressInsideModule(source);        
        $('#basic-modal-content').show();
        $('#basic-modal-content').dialog({
            modal: true,
            width: 550,
            height: 550,
            title: $('#basic-modal-content #MODULE_NAME').val() + ' Settings',
            overlay: { backgroundColor: "#000", opacity: 0.5 },
            close: function(ev, ui) { $('#form1').remove(); $(this).remove();},
            buttons: {                                             
                 "Cancel": function() {
                     $('#form1').remove();
                     $(this).dialog('close');
                  },
                 "Save": function() {                                                
                         //send data to server                                                 
                         // the following serializeArray() function is
                         // tinkerd a bit, this version of serializeArray()
                         // retrieves the form control values by their
                         // css class names, The original gets values by the control id                                                 
                         var serializedData = $('#form1').serializeArray();
                         var jsonData = $.toJSON(serializedData);
                         // the values are html encoded
                         // may be some module settings try to post html data 
                         //                                        [tanvon malik] 25May2010  7:18PM
                         var data = escape(jsonData);                                                    
                         //Pass variable to server using ajax to save state
                         $.post('Admin/Pages/_Modules/ModuleController.aspx?SaveSettings=True', 'data='+ data , function(data){                                                                    
                                            var parent = $(source).parents('.dragbox');
                                            parent.before(data);
                                            parent.remove();                                                                                                                                
                         });                                                 
                         $('#form1').remove();
                         $(this).dialog('close');                                                 
                    }//save
                }//buttons
        });
    });        
}

// design mode progress
function ShowProgress(message){	       
   $('#progress-container #message').text(message);       
   $('#progress-container').show();
}
 
function HideProgress(){	           
   $('#progress-container').hide(); 
}

// design mode progress for module
function ShowProgressInsideModule(source){   
  $(source).parent().before('<span class="error">&nbsp;</span>');   
}
 
function HideProgressInsideModule(source){	           
  $(source).parent().prev('.error').remove();   
}